package com.gxkj.projects.myschoolx.binlog.v1;


import com.gxkj.projects.myschoolx.binlog.v1.model.ColumnInfo;
import com.gxkj.projects.myschoolx.binlog.v1.model.TableInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyTableInfoKeeper {

    private static final Logger logger = LoggerFactory.getLogger(MyTableInfoKeeper.class);

    private static Map<Long,TableInfo> tabledIdMap = new ConcurrentHashMap<>();

    private static Map<String,List<ColumnInfo>> columnsMap = new ConcurrentHashMap<>();

    static{
        columnsMap = MysqlConnectionV8.getColumns();
    }

    public static void saveTableIdMap(long tableId ,String dbName,String tableName){

//        logger.trace("根据tableId从缓存中移除");
        tabledIdMap.remove(tableId);

//        logger.trace("缓存最新的tableId及表信息");
        TableInfo table = new TableInfo();
        table.setDatabaseName(dbName);
        table.setTableName(tableName);
        table.setFullName(dbName+"."+tableName);

        tabledIdMap.put(tableId, table);
    }

    public static synchronized void refreshColumnsMap(){
        Map<String,List<ColumnInfo>> map = MysqlConnectionV8.getColumns();
        if(map.size()>0){
//          logger.warn("refresh and clear cols.");
            columnsMap = map;
//          logger.warn("refresh and switch cols:{}",map);
        }
        else
        {
            logger.error("refresh columnsMap error.");
        }
    }

    public static TableInfo getTableInfo(long tableId){
        return tabledIdMap.get(tableId);
    }

    public static List<ColumnInfo> getColumns(String fullName){
        return columnsMap.get(fullName);
    }
}